<template>
    <div style="height: 60vh;">
        <div id="container" style="width: 100%; height: 100%;"></div>
        <el-button style="margin-top: 12px;" type="primary" @click="startEditing">开始编辑</el-button>
    </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
    props: {
        center: {
            type: Array,
            default: [116.400274, 39.905812]
        },
        range: {
            type: Array,
            default: []
        }
    },
    data() {
        return {
            polygon: null,
            mapContent: null,
        }
    },
    mounted() {
        this.initMap();
    },
    watch: {
        center() {
            console.log('asdasdsadsad');

            this.initMap();
        }
    },
    methods: {
        getSquareBounds(lng, lat, distance) {
            const EARTH_RADIUS = 6378137; // 地球半径，单位米

            // 1°经度对应的距离（赤道附近）：111319米（= 2πR / 360）
            const deltaLng = (distance / (EARTH_RADIUS * Math.cos(lat * Math.PI / 180))) * (180 / Math.PI);
            const deltaLat = (distance / EARTH_RADIUS) * (180 / Math.PI);

            return [
                [lng - deltaLng, lat + deltaLat],// 左上
                [lng + deltaLng, lat + deltaLat],// 右上
                [lng + deltaLng, lat - deltaLat],// 右下
                [lng - deltaLng, lat - deltaLat],// 左下
            ];
        },
        async initMap() {
            // 加载高德地图JS API
            const AMap = await AMapLoader.load({
                key: '559fcb3a8fc70c9be5201519b1eebd0d', // 替换为你的高德地图Key
                version: '2.0',
                plugins: ['AMap.Geocoder', 'AMap.Marker', 'AMap.PolygonEditor']
            })
            const center = this.center;
            console.log('center', center);
            this.mapContent = new AMap.Map("container", {
                center: center,//[116.400274, 39.905812],
                zoom: 16,
                viewMode: '3D',
            });
            let path;
            if (Array.isArray(this.range) && this.range.length > 0) {
                path = this.range.map(i => ([i.lng, i.lat]));
            } else {
                path = this.getSquareBounds(center[0], center[1], 200)
            }
            this.polygon = new AMap.Polygon({
                path: path,
                strokeColor: "#000000",
                strokeWeight: 6,
                strokeOpacity: 0.6,
                fillOpacity: 0.4,
                fillColor: '#1791fc',
                zIndex: 50,
                bubble: true,
            });

            this.mapContent.add(this.polygon);
            this.polyEditor = new AMap.PolygonEditor(this.mapContent, this.polygon);
        },
        startEditing() {
            this.polyEditor.open();
        },
        endEditing() {
            const editedPath = this.polygon.getPath(); // ✅ 直接从 polygon 获取路径
            const editedCoordinates = editedPath.map(point => ({
                lng: point.lng,
                lat: point.lat,
            }));
            this.polyEditor.close();
            return editedCoordinates;
        },
        clearPolygonSelection() {

            // 移除多边形
            if (this.polygon) {
                this.mapContent.remove(this.polygon);
                this.polygon = null;
            }


            // 关闭编辑器
            if (this.polyEditor) {
                this.polyEditor.close();
            }
            // 重置路径
            this.path = [];
        }

    }
};
</script>

<style scoped>
html,
body,
#container {
    width: 100%;
    height: 100%;
}
</style>